const app = getApp();
import * as echarts from '../../../templates/ec-canvas/echarts';
var getAppGlobalData = require('../../../templates/copyright/copyright.js');
Page({
  data: {
    globalData: [],
    Customer: [],//客户的基本信息
    date: '',
    startDate: '',
    page: 1,
    dateindex: 0, //浏览记录加载
    dateindex2: 0, //跟进记录加载
    content: '', //添加跟进记录内容
    BrowseRecords: [], //浏览记录
    followRecords: [], //跟进记录
    index1: '2', //客户活跃度默认时间
    index2: '2', //客户互动默认时间
    Labellist: [],//已有标签
    errno: 0,//该客户是否成交
    types: '',//客户页面传过来的新增还是跟进或者成交
    ai_Interest: [],
    ai_Interest_x: [],
    ai_Interest_y: [],
    ai_active_x: [],
    ai_active_y: [],
    ai_Interaction: [],
    Activitydade: [
      {
        type: '1',
        name: '今天'
      }, {
        type: '2',
        name: '七天'
      }, {
        type: '3',
        name: '30天'
      }], //客户活跃度时间
    interactdade: [
      {
        type: '1',
        name: '今天'
      },
      {
        type: '2',
        name: '七天'
      }, {
        type: '3',
        name: '30天'
      }], //客户互动时间
    firstTime: '',//客户第一次使用时间
    tabList: ['浏览记录', '跟进记录', 'AI分析'],
    currentIndex: 0,
    RecordShow: false, //跟进记录层
    vagueShow: false, //模糊层
    textValue: '', //跟进记录输入内容
    ec: {
      lazyLoad: true // 延迟加载
    },
  },
  // 页面初始化 options为页面跳转所带来的参数 
  onLoad: function (options) {
    // console.log(options)
    options.type ? this.setData({
      types: options.type
    }) : ''
    if (options.id) {
      this.setData({
        id: options.id
      })
    } else {
      this.setData({
        id: '858'
      })
    }

    this.getDealDate();
    this.getRate();
    this.firsttime()

    // //获取客户信息
    // this.shuaxin()

    // //获取用户标签
    // this.biaoqian()

    //获取客户浏览记录
    this.liulan(this.data.page)

    //判断客户是否已成交
    this.ifOK()

    let that = this;

    getAppGlobalData.getAppGlobalData(that);

    var date = new app.util.date();
    var create_time = (date.dateToLong(new Date) / 1000).toFixed(0);
    create_time = date.dateToStr('yyyy-MM-DD', date.longToDate(create_time * 1000));
    that.setData({
      startDate: create_time
    })


    app.util.request({
      'url': 'entry/wxapp/Staff',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': {
        target_id: that.data.id
      },
      success: function (res) {
        // console.log(that.data.Customer)
        //  console.log(res)
        let img2 = res.data.data.avatarUrl
        that.setData({
          img2: img2
        })
      }
    })
  },
  listenerDatePickerSelected: function (e) {
    let that = this;
    let tmpData = e.detail.value;
    var tmpArr = tmpData.split('-');
    that.setData({
      date: tmpData,
      month: tmpArr[1],
      day: tmpArr[2],
      content:'将预计成交日期更改为'+tmpData
    })
    that.getDealDate();
    that.adds();
  },
  getDealDate:function(){
    var that = this;
    let paramObj = {
      client_id: that.data.id, 
    }
    if(that.data.date){
      paramObj.date = that.data.date
    }
    app.util.request({
      'url': 'entry/wxapp/DealDate',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': paramObj,
      success: function (res) {
        console.log("entry/wxapp/DealDate ==> ",res)
        if (!res.data.errno) {
          let tmpData = res.data.data.date;
          var tmpArr = tmpData.split('-');
          that.setData({
            date: tmpData,
            month: tmpArr[1],
            day: tmpArr[2]
          })
        }
      }
    })
  },
  getRate:function(){
    var that = this;
    let paramObj = {
      client_id: that.data.id, 
    }
    app.util.request({
      'url': 'entry/wxapp/Rate',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': paramObj,
      success: function (res) {
        console.log("entry/wxapp/Rate ==> ",res)
        if (!res.data.errno) { 
          that.setData({
            rate : res.data.data.rate
          })
        }
      }
    })
  },
  //修改编辑客户信息
  Edit: function (e) {
    wx.navigateTo({
      url: `/longbing_card/staff/custom/editInfo/editInfo?id=${this.data.id}`,
    })
  },
  //切换tabs
  tabsSwitch: function (e) {
    let index = e.currentTarget.dataset.index
    let that = this

    this.setData({
      currentIndex: index,
      page: 1,
      BrowseRecords: [], //浏览记录
      followRecords: [], //跟进记录
      ai_Interest: [],
      ai_Interest_x: [],
      ai_Interest_y: [],
      ai_active_x: [],
      ai_active_y: [],
      ai_Interaction: [],
    })

    if (index == 2) {
      that.aifenxi()
    } else if (index == 1) {
      //获取客户跟进记录
      that.genjin()
    } else if (index == 0) {
      this.liulan()
    }

  },
  //跳转添加标签页面
  addslables: function (e) {
    wx.navigateTo({
      url: `/longbing_card/staff/custom/tag/tag?id=${this.data.id}`,
    })
  },
  //点击添加跟进记录按钮
  addsRecord: function (e) {
    this.setData({
      RecordShow: true, //跟进记录层
      vagueShow: true, //模糊层
      content: ''
    })
  },
  //跟进记录input
  textValue: function (e) {
    // console.log(e.detail.value)
    this.setData({
      content: e.detail.value
    })
  },
  //取消
  cancel: function (e) {
    this.setData({
      RecordShow: false, //跟进记录层
      vagueShow: false, //模糊层
      textValue: '', //跟进记录输入内容
    })
  },
  //保存
  adds: function (e) {
    let that = this
    that.setData({
      RecordShow: false, //跟进记录层
      vagueShow: false, //模糊层
    })
    app.util.request({
      'url': 'entry/wxapp/followInsert',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': {
        client_id: this.data.id,
        content: this.data.content
      },
      success: function (res) {
        // console.log("entry/wxapp/formid ==>", res)
        if (!res.data.errno) {
          that.genjin()
          that.setData({
            content : ''
          })
        }
      }
    })
  },
  index99: function (e) {
    this.setData({
      RecordShow: false, //跟进记录层
      vagueShow: false, //模糊层
      textValue: '', //跟进记录输入内容
    })
  },
  onReady: function () {

  },
  // 页面显示 
  onShow: function (e) {
    //获取客户信息
    this.shuaxin()
    //获取用户标签
    this.biaoqian()
  },
  onHide: function () {
    // console.log("页面隐藏")
  },
  onUnload: function () {
    // console.log("页面关闭")
  },
  // console.log("监听用户下拉动作")  
  onPullDownRefresh: function () {
    this.setData({
      page: 1,
      dateindex2: 0,
      content: '', //添加跟进记录内容
      currentIndex: 0,
      BrowseRecords: [], //浏览记录
      followRecords: [], //跟进记录
    })
    //获取客户浏览记录
    this.liulan(this.data.page)
    wx.stopPullDownRefresh()
  },
  // console.log("监听页面上拉触底")
  onReachBottom: function () {

    let firstTime = this.data.firstTime
    let index = this.data.currentIndex
    let that = this
    let page = this.data.page
    page++
    if (index == 0) {
      this.setData({
        page: page
      })
      //获取客户浏览记录
      this.liulan(page)

    } else if (index == 1) {
      //获取用户跟进记录

      let index2 = this.data.dateindex2
      index2--
      function formatTime(date) {
        var year = date.getFullYear();
        var month = date.getMonth() + 1,
          month = month < 10 ? '0' + month : month;
        var day = date.getDate(),
          day = day < 10 ? '0' + day : day;
        return year + '/' + month + '/' + day;
      }
      var times = new Date(); //Wed Jul 05 2017 13:50:11 GMT+0800 (中国标准时间)
      //增加天数 月 年等
      times.setDate(times.getDate() + this.data.dateindex2)

      times.setDate(times.getDate() + index2)
      let time = JSON.stringify(Date.parse(formatTime(times))).substring(0, 10)

      if ((time - firstTime) > 0) {
        // console.log(time - firstTime)
        this.setData({
          dateindex2: index2
        })
        //获取客户跟进记录
        this.genjin(time)
      }
      // else{
      //   wx.showToast({
      //     title: '没有更多数据了'
      //   })
      // }

    }
  },
  onPageScroll: function (e) {
    //console.log("监听页面滚动", e);
  },
  onShareAppMessage: function (res) {
    // console.log("用户点击右上角分_享") 
  },
  bindPickerChange2: function (e) {

    this.setData({
      index1: e.detail.value
    })
    let index = parseInt(this.data.index1) + 1
    this.aifenxi({ type: '1', types: index })
  },
  bindPickerChange3: function (e) {
    console.log(e)
    this.setData({
      index2: e.detail.value
    })
    let index = parseInt(this.data.index2) + 1
    this.aifenxi({ type: '2', types: index })
  },

  BottomOK: function (e) {
    let that = this
    if (this.data.errno == '1') {
      app.util.request({
        'url': 'entry/wxapp/Deal',
        'cachetime': '30',
        'showLoading': false,
        'method': 'POST',
        'data': {
          client_id: this.data.id
        },
        success: function (res) {

          if (!res.data.errno) {
            that.setData({
              errno: '0'
            })
          }
        }
      })
    }
  },
  ifOK: function (e) {
    let that = this
    app.util.request({
      'url': 'entry/wxapp/CheckDeal',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': {
        client_id: this.data.id
      },
      success: function (res) {
        if (!res.data.errno) {
          let aa = res.data.message == '未成交' ? '1' : '0'
          that.setData({
            errno: aa
          })
        }
      }
    })
  },

  init_bar: function (e) {
    var self = this;
    if (e == '1') {
      //pre
      this.barComponent.init(function (canvas, width, height) {
        // 初始化图表
        const barChart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        barChart.setOption(self.getBarOption());
        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return barChart;
      })
    }
    if (e == '2') {
      //line
      this.barComponent2.init(function (canvas, width, height) {
        // 初始化图表
        const barChart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        barChart.setOption(self.getBarOption2());
        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return barChart;
      })
    }


  },
  getBarOption: function () {
    // console.log(JSON.stringify(this.data.tatallData));
    var that = this;
    // console.log(that.data.ai_Interest_y)
    // console.log(that.data.ai_Interest_x)

    return {
      legend: {
        orient: 'vertical',
        top: '10%',
        right: '10%',
        data: that.data.ai_Interest_x
      },
      series: [{
        type: 'pie',
        center: ['30%', '40%'],
        radius: ['40%', '60%'],
        avoidLabelOverlap: false,
        label: {
          normal: {
            show: false,
            position: 'center'
          },
          // emphasis: {
          //   show: true,
          //   textStyle: {
          //     fontSize: '30',
          //     fontWeight: 'bold'
          //   }
          // }
        },
        data: that.data.ai_Interest_y
      }]
    }
  },
  getBarOption2: function () {
    // console.log(JSON.stringify(this.data.tatallData));
    var that = this;
    return {
      grid: {
        left: '15%',
        right: '15%',
        top: '10%',
        bottom: '15%'
      },
      xAxis: {
        type: 'category',
        minInterval: '100',
        boundaryGap: false,
        minInterval: '1',
        data: that.data.ai_active_x,
        axisLabel: {
          showMinLabel: true
        }
      },
      yAxis: {
        type: 'value'
      },

      series: [{
        symbol: 'none',
        data: that.data.ai_active_y,
        type: 'line',
        areaStyle: {
          color: '#e89e9e',
        }
      }]
    }
  },

  //浏览记录
  liulan: function (page) {
    // console.log(page)
    let that = this
    let newdata = {}
    newdata.client_id = this.data.id
    if (page) {
      newdata.page = page
    } else {
      this.setData({
        BrowseRecords: []
      })
    }
    app.util.request({
      'url': 'entry/wxapp/clientView',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': newdata,
      success: function (res) {
        // console.log(res)
        let reslist = []
        for (let i in res.data.data.list) {
          reslist.push(res.data.data.list[i])
        }
        if (reslist.length > 0 && !res.data.errno) {
          function timestampToTime(timestamp) {
            var date = new Date(timestamp * 1000);
            // var Y = date.getFullYear() + '-';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            var D = (date.getDate() + 1 < 10 ? '0' + (date.getDate() + 1) : date.getDate() + 1) + ' ';
            var h = (date.getHours() + 1 < 10 ? '0' + (date.getHours() + 1) : date.getHours() + 1) + ':';
            var m = (date.getMinutes() + 1 < 10 ? '0' + (date.getMinutes() + 1) : date.getMinutes() + 1);
            return M + D + h + m
          }
          let data = res.data.data
          let datas = that.data.BrowseRecords
          reslist.forEach(val => {
            val.dates = timestampToTime(val.create_time)
          })
          datas.push(data)

          that.setData({
            BrowseRecords: datas
          })
          // console.log(datas)
          let adds = []
          datas.forEach(val => {
            let value = []
            for (let i in val.list) {
              value.push(val.list[i])
            }
            value.forEach(val => {
              adds.push(val)
            })
          })

          if (adds.length < 5) {
            that.onReachBottom()
          }
        }
      }
    })
  },
  genjin: function (time) {
    let that = this
    let newdata = {}
    newdata.client_id = that.data.id
    if (time) {
      newdata.date = time
    } else {
      this.setData({
        followRecords: []
      })
    }
    app.util.request({
      'url': 'entry/wxapp/followList',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': newdata,
      success: function (res) {
        if (res.data.data.data.length > 0 && !res.data.errno) {
          function timestampToTime(timestamp) {
            var date = new Date(timestamp * 1000);
            var h = date.getHours() + ':';
            var m = date.getMinutes();
            return h + m
          }
          let data = res.data.data
          let datas = that.data.followRecords
          res.data.data.data.forEach(val => {
            val.dates = timestampToTime(val.create_time)
          })
          datas.push(data)
          that.setData({
            followRecords: datas
          })

          let adds = []
          datas.forEach(val => {
            val.data.forEach(val => {
              adds.push(val)
            })
          })

          if (adds.length < 5) {
            that.onReachBottom()
          }
        }
        // else{
        //   wx.showToast({
        //     title:'没有更多数据了'
        //   })
        // }
      }
    })
  },
  aifenxi: function (e) {
    var self = this;
    let that = this
    let index = 1
    if (e) {

      index = e.types
      if (e.type == '0') {
        //客户兴趣
        app.util.request({
          'url': 'entry/wxapp/Interest',
          'cachetime': '30',
          'showLoading': false,
          'method': 'POST',
          'data': {
            client_id: this.data.id,
          },
          success: function (res) {
            // console.log("entry/wxapp/formid ==>", res)
            if (!res.data.errno) {
              // console.log('1')
              // console.log(res)
              let data = res.data.data
              let xx = []
              let yy = []
              if (data.qr) {
                xx.push(`名片${data.qr.count}(${data.qr.rate}%)`)
                yy.push({ value: data.qr.count, name: `名片${data.qr.count}(${data.qr.rate}%)` })
              }
              if (data.timeline) {
                xx.push(`动态${data.timeline.count}(${data.timeline.rate}%)`)
                yy.push({ value: data.timeline.count, name: `动态${data.timeline.count}(${data.timeline.rate}%)` })
              }
              if (data.goods) {
                xx.push(`产品${data.goods.count}(${data.goods.rate}%)`)
                yy.push({ value: data.goods.count, name: `产品${data.goods.count}(${data.goods.rate}%)` })
              }
              if (data.custom_qr) {
                xx.push(`自定义码${data.custom_qr.count}(${data.custom_qr.rate}%)`)
                yy.push({ value: data.custom_qr.count, name: `自定义码${data.custom_qr.count}(${data.custom_qr.rate}%)` })
              }

              that.setData({
                ai_Interest_x: xx,
                ai_Interest_y: yy
              })

              self.barComponent = self.selectComponent('#mychart');
              self.init_bar('1'); //执行init_bar方法
            }
          }
        })
      } else if (e.type == '1') {
        //客户活跃度
        app.util.request({
          'url': 'entry/wxapp/Activity',
          'cachetime': '30',
          'showLoading': false,
          'method': 'POST',
          'data': {
            client_id: this.data.id,
            type: index
          },
          success: function (res) {
            // console.log("entry/wxapp/formid ==>", res)
            if (!res.data.errno) {
              // console.log('2')
              // console.log(res)
              let data = res.data.data.reverse()
              let xx = []
              let yy = []
              data.forEach(val => {
                let aa = val.date
                xx.push(aa.slice(5))
                yy.push(val.count)
              })
              that.setData({
                ai_active_x: xx,
                ai_active_y: yy,
              })
              self.barComponent2 = self.selectComponent('#mychart2');
              self.init_bar('2'); //执行init_bar方法
            }
          }
        })
      }
      else if (e.type == '2') {
        //互动
        app.util.request({
          'url': 'entry/wxapp/clientInteraction',
          'cachetime': '30',
          'showLoading': false,
          'method': 'POST',
          'data': {
            client_id: this.data.id,
            type: index
          },
          success: function (res) {
            // console.log("entry/wxapp/formid ==>", res)
            if (!res.data.errno) {
              // console.log('3')
              // console.log(res)
              let data = res.data.data
              for (let i in data) {
                let width = parseInt(data[i].rate / 100 * 200)
                data[i].width = width
              }
              // console.log(data)
              that.setData({
                ai_Interaction: data
              })
            }
          }
        })
      }
    } else {
      //客户兴趣
      app.util.request({
        'url': 'entry/wxapp/Interest',
        'cachetime': '30',
        'showLoading': false,
        'method': 'POST',
        'data': {
          client_id: this.data.id,
        },
        success: function (res) {
          // console.log("entry/wxapp/formid ==>", res)
          if (!res.data.errno) {
            // console.log('1')
            // console.log(res)
            let data = res.data.data
            console.log(data)
            let xx = []
            let yy = []

            if (data.qr) {
              xx.push(`名片${data.qr.count}(${data.qr.rate}%)`)
              yy.push({ value: data.qr.count, name: `名片${data.qr.count}(${data.qr.rate}%)` })
            }
            if (data.timeline) {
              xx.push(`动态${data.timeline.count}(${data.timeline.rate}%)`)
              yy.push({ value: data.timeline.count, name: `动态${data.timeline.count}(${data.timeline.rate}%)` })
            }
            if (data.goods) {
              xx.push(`产品${data.goods.count}(${data.goods.rate}%)`)
              yy.push({ value: data.goods.count, name: `产品${data.goods.count}(${data.goods.rate}%)` })
            }
            if (data.custom_qr) {
              xx.push(`自定义码${data.custom_qr.count}(${data.custom_qr.rate}%)`)
              yy.push({ value: data.custom_qr.count, name: `自定义码${data.custom_qr.count}(${data.custom_qr.rate}%)` })
            }

            that.setData({
              ai_Interest_x: xx,
              ai_Interest_y: yy
            })

            self.barComponent = self.selectComponent('#mychart');
            self.init_bar('1'); //执行init_bar方法
          }
        }
      })
      //客户活跃度
      app.util.request({
        'url': 'entry/wxapp/Activity',
        'cachetime': '30',
        'showLoading': false,
        'method': 'POST',
        'data': {
          client_id: this.data.id,
          type: index
        },
        success: function (res) {
          // console.log("entry/wxapp/formid ==>", res)
          if (!res.data.errno) {
            // console.log('2')
            // console.log(res)
            let data = res.data.data.reverse()
            let xx = []
            let yy = []

            data.forEach(val => {
              let aa = val.date
              xx.push(aa.slice(5))
              yy.push(val.count)
            })
            that.setData({
              ai_active_x: xx,
              ai_active_y: yy,
            })
            self.barComponent2 = self.selectComponent('#mychart2');
            self.init_bar('2'); //执行init_bar方法
          }
        }
      })
      //互动
      app.util.request({
        'url': 'entry/wxapp/clientInteraction',
        'cachetime': '30',
        'showLoading': false,
        'method': 'POST',
        'data': {
          client_id: this.data.id,
          type: index
        },
        success: function (res) {
          // console.log("entry/wxapp/formid ==>", res)
          if (!res.data.errno) {
            // console.log('3')
            // console.log(res)
            let data = res.data.data
            for (let i in data) {
              let width = parseInt(data[i].rate / 100 * 200)
              data[i].width = width
            }
            // console.log(data)
            that.setData({
              ai_Interaction: data
            })
          }
        }
      })

    }
  },

  //用户信息
  shuaxin: function (e) {
    let that = this
    app.util.request({
      'url': 'entry/wxapp/clientInfo',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': {
        client_id: that.data.id
      },
      success: function (res) {
        // console.log("entry/wxapp/formid ==>", res)
        if (!res.data.errno) {

          let data = res.data.data
          if (data.is_new == '1') {
            data.value1 = '新客户'
          } else if (data.is_new == '2') {
            data.value1 = '跟进中'
          } else if (data.is_new == '3') {
            data.value1 = '已成交'
          }
          that.setData({
            Customer: data
          })
          console.log(data)
        }
      }
    })
  },
  firsttime: function () {
    let that = this
    app.util.request({
      'url': 'entry/wxapp/firstTime',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': {
        client_id: this.data.id
      },
      success: function (res) {
        // console.log("entry/wxapp/formid ==>", res)
        if (!res.data.errno) {
          // console.log(res)
          that.setData({
            firstTime: res.data.data.time
          })
        }
      }
    })
  },
  biaoqian: function () {
    let that = this
    app.util.request({
      'url': 'entry/wxapp/Labels',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': {
        target_id: that.data.id
      },
      success: function (res) {
        // console.log(res)
        // console.log("entry/wxapp/formid ==>", res)
        if (!res.data.errno) {
          that.setData({
            Labellist: res.data.data
          })
        }
      }
    })
  },
  qq: function () {
    let that = this
    let id = this.data.id
    let name = that.data.Customer.nickName
    let img1 = that.data.Customer.avatarUrl

    app.util.request({
      'url': 'entry/wxapp/Staff',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': {
        target_id: that.data.id
      },
      success: function (res) {
        // console.log(that.data.Customer)
        //  console.log(res)
        let img2 = res.data.data.avatarUrl
        wx.navigateTo({
          url: `/longbing_card/chat/staffChat/staffChat?chat_to_uid=${id}&contactUserName=${name}&chatAvatarUrl=${img1}&toChatAvatarUrl=${img2}`
        })
      }
    })
  },
})